/*Kịch bản 1: 1 Quản lý xem danh sách Khuyến mãi, thì 1 Quản lý khác thêm 1 Khuyến mãi

*/
alter proc sp_SelectKhuyenMaiByMaMonAn
	@Ma_MonAn nchar(3),
	@soKM int out

as
begin tran	
	set tran isolation level serializable
	set @soKM = (select count(*) from KhuyenMai WHERE Ma_MonAn=@Ma_MonAn)

	waitfor delay '0:0:03'
	SELECT Ma_KhuyenMai,Ma_MonAn,PhanTramGiam,NgayBatDau,NgayKetThuc FROM KhuyenMai WHERE Ma_MonAn=@Ma_MonAn
commit tran
go


ALTER PROCEDURE [dbo].[sp_InsertKhuyenMai]
	@Ma_KhuyenMai nchar (3),
	@Ma_MonAn nchar (3),
	@PhanTramGiam int,
	@NgayBatDau datetime,
	@NgayKetThuc datetime
AS
BEGIN TRAN
	DECLARE  @NBD datetime
	DECLARE @NKT datetime
	DECLARE @cur CURSOR
	DECLARE @FLAG int
	SET @FLAG=0
	SET @cur= CURSOR FOR (SELECT NgayBatDau,NgayKetThuc FROM KhuyenMai WHERE Ma_MonAn=@Ma_MonAn)
	OPEN @cur
	FETCH NEXT FROM @cur INTO @NBD,@NKT
	WHILE @@fetch_status = 0
	BEGIN
		IF((@NgayBatDau between @NBD and @NKT)OR (@NgayKetThuc between @NBD and @NKT) OR ((@NBD between @NgayBatDau and @NgayKetThuc) and (@NKT between @NgayBatDau and @NgayKetThuc)) )
		BEGIN
				SET @FLAG=1
		END
		
		FETCH NEXT FROM @cur INTO @NBD,@NKT
	END
	
	
	IF(@FLAG=0)
	BEGIN
		INSERT INTO KhuyenMai VALUES(@Ma_KhuyenMai,@Ma_MonAn,@PhanTramGiam,@NgayBatDau,@NgayKetThuc)
	END
	close @cur
	deallocate @cur
COMMIT TRAN